package com.xoa.service.cms;

import com.xoa.model.cms.CmsChannelInfo;
import com.xoa.model.cms.CmsSiteInfo;
import com.xoa.model.cms.SiteTemplateModel;
import com.xoa.service.cms.core.CmsTemplateUtil;
import com.xoa.service.cms.core.FileUtils;
import com.xoa.service.enclosure.EnclosureService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.ResourceBundle;

/**
 * Created by cyt on 2018/7/7.
 */
@Service
public class CmsSitePublishService {
    @Autowired
    private CmsSiteService siteService;

    @Autowired
    private CmsSiteTemplateService siteTemplateService;

    @Autowired
    private CmsChannelService channelService;

    @Autowired
    private CmsChannelPublishService channelPublishService;

    @Autowired
    private CmsDocumentService documentService;

    @Autowired
    private EnclosureService attachmentService;




    /**
     * 全站发布
     *
     * @param siteId
     * @param
     */
    public void toPub(HttpServletRequest request,int siteId, boolean fullPub) {
        // 获取站点信息
        CmsSiteInfo siteModel = siteService.getSiteInfo(siteId);
        // 获取站点模板
        SiteTemplateModel indexTpl = siteTemplateService.getSiteTemplate(siteModel.getIndexTpl());
        if (indexTpl != null) {// 如果存在首页模板，则进行渲染
            String path=request.getRealPath("cmstpls");
            Configuration config = new Configuration();
            ByteArrayOutputStream baos = null;
            Writer out = null;
            FileOutputStream fos=null;
            try {
                config.setDirectoryForTemplateLoading(new File(path));

                // 注入服务
                config.setCustomAttribute("attachmentService", attachmentService);
                config.setCustomAttribute("siteService", siteService);
                config.setCustomAttribute("siteTemplateService",siteTemplateService);
                config.setCustomAttribute("channelService", channelService);
                config.setCustomAttribute("documentService", documentService);

                // 附加参数
                config.setCustomAttribute("ROOT_PATH", "./");
                config.setCustomAttribute("SITE_ID", siteModel.getSid());

                Template template = config.getTemplate(indexTpl.getTplFileName(), "UTF-8");
                baos = new ByteArrayOutputStream();
                out = new OutputStreamWriter(baos, "UTF-8");
                config.setCustomAttribute("preview", false);
                // 输出参数
                template.process(CmsTemplateUtil.getInstance(), out);
                out.flush();
                out.close();
                //发布对应的资源文件
                this.copyResource(request,siteId);
                //生成对应的静态文件
                String outPath = siteModel.getFolder()+"\\";
                File file = new File(outPath);
                if(!file.exists()){
                    file.mkdirs();
                }
                fos = new FileOutputStream(new File(outPath+"index."+siteModel.getPubFileExt()));
                baos.writeTo(fos);
                if(fullPub){
                    List<CmsChannelInfo> channelList = channelService.getTopChannels(siteId, Integer.MAX_VALUE);
                    for(int i = 0; i<channelList.size();i++){
                        channelPublishService.toPub(request,channelList.get(i).getSid(), true);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (baos != null) {
                    try {
                        baos.close();
                    } catch (IOException e) {
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                    }
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }
    public void copyResource(HttpServletRequest request,int siteId){
        CmsSiteInfo siteModel = siteService.getSiteInfo(siteId);
        //String srcPath=TeeSysProps.getRootPath()+"cmstpls/"+siteId;
        //            ResourceBundle rb =  ResourceBundle.getBundle("cms");
//            String path = rb.getString("rootPath")+ System.getProperty("file.separator")+indexTpl.getSiteId();
        String pathsrc=request.getRealPath("cmstpls");
        String srcPath = pathsrc+ System.getProperty("file.separator")+siteId;
        String destPath=siteModel.getFolder()+"/";
        File file= new File(srcPath);
        File[] files = file.listFiles();
        if(null!=files){
            for(File f:files){
                if(f.isDirectory()){
                    FileUtils.copyDirs(f.getAbsolutePath(), destPath+"/"+f.getName());
                }
            }
        }
    }
}
